<template>
  <t-modal
    title="版本对比"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    wrapClassName="version-container"
    v-bind="footer"
    forceRender
  >
    <div class="curve-modal-body">
      <div class="screen-search">
        <div>模型名称：</div>
        <a-tree-select
          v-model="condition.dataSetId"
          treeNodeFilterProp="title"
          show-search
          style="width: 300px"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          searchPlaceholder="请输入"
          tree-default-expand-all
          :replaceFields="{
            children: 'subNodes',
            title: 'nodeName',
            key: 'dataSetId',
            value: 'dataSetId',
          }"
          :tree-data="treeData"
          @change="changeModel"
        >
        </a-tree-select>
      </div>
      <div class="custom-tabs-box">
        <div class="tabs-item-box">
          <div
            class="tab-box"
            :class="[tabsActiveIndex == 1 && 'active']"
            @click="handelTabs(1)"
          >
            变更日志({{ count }})
          </div>
          <div
            class="tab-box"
            :class="[tabsActiveIndex == 2 && 'active']"
            @click="handelTabs(2)"
          >
            版本对比
          </div>
        </div>
        <div class="tabs-content-box">
          <div class="update-container" v-if="tabsActiveIndex == 2">
            <div class="update-item">
              <div>更新前版本：</div>
              <a-select
                v-model="condition.versionFront"
                placeholder="请选择"
                style="width: 153px"
              >
                <a-select-option
                  :value="item.version"
                  v-for="item in versionSoucre"
                  :key="item.versionId"
                >
                  V{{ item.version }}
                </a-select-option>
              </a-select>
            </div>
            <div class="update-item">
              <icon-fonts icon="icon-xiaozuduibi"></icon-fonts>
            </div>
            <div class="update-item">
              <div>更新后版本：</div>
              <a-select
                v-model="condition.versionAfter"
                placeholder="请选择"
                style="width: 153px"
              >
                <a-select-option
                  :value="item.version"
                  v-for="item in versionSoucre"
                  :key="item.versionId"
                >
                  V{{ item.version }}
                </a-select-option>
              </a-select>
            </div>
            <div class="update-item" v-if="buttonFlag">
              <a-button class="cu-btn-primary" @click="handelInitiate()">
                发起对比
              </a-button>
            </div>
          </div>
          <div class="main">
            <vxe-table
              ref="xTable"
              :height="scrollHeight"
              align="center"
              border="inner"
              size="small"
              show-overflow
              show-header-overflow
              :data="tableData"
              :column-config="{ resizable: true }"
              :loading="loading"
              :key="vxeKey"
            >
              <vxe-column
                :title="item.title"
                :field="item.key"
                :key="index"
                v-for="(item, index) in columns"
              >
                <template #default="{ row }">
                  <div v-if="item.key == 'version'">V{{ row[item.key] }}</div>
                  <div
                    v-else-if="item.key == 'statusDes'"
                    :class="[checkClassName(row.status)]"
                  >
                    ● {{ row[item.key] }}
                  </div>
                  <div v-else-if="item.key == 'contrastTime'">
                    {{ getDataStr(row) }}
                  </div>
                  <div v-else>{{ row[item.key] }}</div>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <div class="text-button-group">
                    <a-button type="link" @click="handeView(row)">
                      查看模型
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
  </t-modal>
</template>

<script>
import { addAttributeByKey } from "@/utils/util.js";
import {
  getModalTreeById,
  versionHistory,
  supportInvariantUniqueId,
  versionContrast,
  initiateVersionContrast,
} from "@/api/bim";
export default {
  inject: ["currentProject", "sceneSource"],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    footer: {
      type: Object,
      default() {
        return {
          footer: null,
        };
      },
    },
  },
  data() {
    return {
      tabsActiveIndex: 1,
      treeData: [],
      //列表
      count: 0,
      vxeKey: 0,
      scrollHeight: "455px",
      columns: [
        {
          title: "版本号",
          key: "version",
        },
        {
          title: "转换完成时间",
          key: "updateTime",
        },
      ],
      loading: false,
      tableData: [],
      versionSoucre: [],
      condition: {
        //模型
        dataSetId: undefined,
        //更新前
        versionFront: undefined,
        //更新后
        versionAfter: undefined,
      },
      currentTree: {},
      buttonFlag: false,
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getTreeData();
        } else {
          this.resetData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getDataStr(row) {
      let { contrastTime } = row;
      if (contrastTime) {
        let formattedDate = contrastTime.substring(0, 19);
        const newStr = formattedDate.replace(/T/g, " ");
        return newStr;
      }
    },

    changeModel(value, label, extra) {
      this.currentTree = extra.triggerNode.dataRef;
      this.tabsActiveIndex = 1;
      this.handleActive();
    },
    handelTabs(type) {
      this.tabsActiveIndex = type;
      this.handleActive();
    },

    handleActive() {
      let { tabsActiveIndex } = this;
      switch (tabsActiveIndex) {
        case 1:
          this.vxeKey = Date.now();
          this.scrollHeight = "455px";
          this.columns = [
            {
              title: "版本号",
              key: "version",
            },
            {
              title: "转换完成时间",
              key: "updateTime",
            },
          ];
          this.getVersionHistoryData();
          break;

        case 2:
          this.vxeKey = Date.now();
          this.scrollHeight = "413px";
          this.columns = [
            {
              title: "对比版本",
              key: "versionDesc",
            },
            {
              title: "对比状态",
              key: "statusDes",
            },
            {
              title: "对比时间",
              key: "contrastTime",
            },
          ];
          let first = 0;
          let final = this.versionSoucre.length - 1;
          //更新前
          this.condition.versionFront = this.versionSoucre?.[final].version;
          //更新后
          this.condition.versionAfter = this.versionSoucre?.[first].version;
          this.getSupportData();
          this.getVersionContrastData();
          break;

        default:
          break;
      }
    },

    //查看模型
    handeView(row) {
      let { tabsActiveIndex } = this;
      let { dataSetId, nodeName } = this.currentTree;
      let path = "";
      let params = {};
      switch (tabsActiveIndex) {
        //变更日志
        case 1:
          let { versionId } = row;
          params = {
            // token: getToken(),
            dataSetId,
            nodeName,
            versionId,
          };
          path = `/blackHole/versionView`;
          break;
        //版本对比
        case 2:
          let { fromVersion, toVersion } = row;
          params = {
            dataSetId,
            nodeName,
            fromVersion,
            toVersion,
            // token: getToken(),
          };
          path = `/blackHole/versionCompare`;
          break;
        default:
          break;
      }
      let domain = location.origin;
      window.open(`${domain}/#${path}?data=${JSON.stringify(params)}`);
    },

    //查询树列表
    getTreeData() {
      return new Promise((resolve, reject) => {
        let { foreignUuid } = this.currentProject();
        if (!foreignUuid) {
          return;
        }
        getModalTreeById({ projId: foreignUuid })
          .then((res) => {
            let { data } = res;
            let tree = data?.subNodes ?? [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              tree,
              "subNodes"
            );
            this.treeData = filterData;
            this.condition.dataSetId = this.treeData?.[0]?.dataSetId ?? [];
            this.currentTree = this.treeData?.[0] ?? {};
            this.getVersionHistoryData();
            resolve();
          })
          .catch((_) => {
            this.currentTree = {};
            this.condition.dataSetId = undefined;
            this.treeData = [];
            reject();
          });
      });
    },
    //查询变更日志
    getVersionHistoryData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { dataSetId } = this.condition;
        versionHistory({
          nodeId: dataSetId,
        })
          .then((res) => {
            this.tableData = res?.data ?? [];
            this.versionSoucre = res?.data ?? [];
            this.count = this.tableData.length;
            resolve();
          })
          .catch((_) => {
            this.count = 0;
            this.versionSoucre = [];
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //查询版本对比权限
    getSupportData() {
      return new Promise((resolve, reject) => {
        let { dataSetId } = this.condition;
        supportInvariantUniqueId({
          dataSetId,
        })
          .then((res) => {
            this.buttonFlag = res.data;
            resolve();
          })
          .catch((_) => {
            this.buttonFlag = false;
            reject();
          });
      });
    },
    //查询版本对比
    getVersionContrastData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { dataSetId } = this.condition;
        versionContrast({
          dataSetId,
        })
          .then((res) => {
            this.tableData = res?.data?.items ?? [];
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //发起版本对比
    handelInitiate() {
      let { dataSetId, versionFront, versionAfter } = this.condition;
      if (versionFront >= versionAfter) {
        return this.$message.warning("更新前的版本号必须小于更新后的版本号");
      }
      return new Promise((resolve, reject) => {
        initiateVersionContrast({
          DataSetId: dataSetId,
          FromVersion: versionFront,
          ToVersion: versionAfter,
        })
          .then((res) => {
            let { data } = res;
            this.getVersionContrastData();
            if (data?.errMsg) {
              this.$message.warning(data?.errMsg, 1.5);
            }
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    checkClassName(status) {
      switch (status) {
        case 1:
          return "success";

        case -1:
          return "fail";

        default:
          return "ing";
      }
    },

    resetData() {
      this.tabsActiveIndex = 1;
      this.treeData = [];
      this.count = 0;
      this.vxeKey = 0;
      this.scrollHeight = "455px";
      this.columns = [
        {
          title: "版本号",
          key: "version",
        },
        {
          title: "转换完成时间",
          key: "updateTime",
        },
      ];
      this.loading = false;
      this.tableData = [];
      this.versionSoucre = [];
      this.condition = {
        //模型
        dataSetId: undefined,
        //更新前
        versionFront: undefined,
        //更新后
        versionAfter: undefined,
      };
      this.buttonFlag = false;
    },

    closeModal() {
      this.$emit("update:visible", false);
      this.$emit("close");
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.version-container {
  .curve-modal-body {
    height: 500px;
    display: flex;
    flex-direction: column;
    .screen-search {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
    .custom-tabs-box {
      flex: 1;
      display: flex;
      flex-shrink: 0;
      .tabs-item-box {
        width: 240px;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #d9d9d9;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px 0;
        box-sizing: border-box;
        .tab-box {
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          width: 200px;
          height: 40px;
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 14px;
          color: #333333;
          border: 1px solid #d9d9d9;
          margin-bottom: 20px;
          border-radius: 4px 4px 4px 4px;
          &.active {
            background: rgba(22, 119, 255, 0.1);
            color: #1677ff;
          }
          &:hover {
            background: rgba(22, 119, 255, 0.1);
          }
        }
      }
      .tabs-content-box {
        flex: 1;
        flex-shrink: 0;
        padding-left: 10px;
        display: flex;
        flex-direction: column;
        .update-container {
          display: flex;
          .update-item {
            display: flex;
            align-items: center;
            margin: 0 0 10px 12px;
            .middle {
              font-size: 22px !important;
            }
            &:first-of-type {
              margin-left: 0;
            }
            .ant-btn {
              margin-right: 0 !important;
            }
          }
        }
        .main {
          flex: 1;
          .success {
            color: #4bc964;
          }
          .fail {
            color: #ff3f4a;
          }
          .ing {
            color: #0098ff;
          }
        }
      }
    }
  }
}
</style>
